package com.eobjectsoft.etranslator.popup.actions;

import com.eobjectsoft.etranslator.ETranslatorPlugin;
import com.eobjectsoft.etranslator.ETranslatorResources;
import com.eobjectsoft.etranslator.core.TranslateCore;
import com.eobjectsoft.etranslator.engine.TranslateEngine;
import com.eobjectsoft.etranslator.engine.TranslateMode;
import com.eobjectsoft.etranslator.utils.LOG;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.*;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.*;

public class TranslateAction
    implements IObjectActionDelegate
{
	/**
	 * keep the current selection
	 */
	ISelection curSel;
	
    public TranslateAction()
    {
    }

    public void setActivePart(IAction iaction, IWorkbenchPart iworkbenchpart)
    {
    }

    public void run(IAction action)
    {
    	//get current selected file
        IFile selFile = (IFile)((StructuredSelection)curSel).getFirstElement();
        String sourceFile = selFile.getRawLocation().toOSString();
        try
        {
        	//translate the selected resource file
            TranslateWithProgress translate = new TranslateWithProgress();
            translate.sourceFile = sourceFile;
            (new ProgressMonitorDialog(
            		Display.getCurrent().getActiveShell())).run(true, true, translate);
        }
        catch(InvocationTargetException targetExp) {
        	LOG.error(targetExp);
        }
        catch(InterruptedException interuptExp) { 
        	LOG.error(interuptExp);
        }
    }

    public void selectionChanged(IAction action, ISelection selection)
    {
        curSel = selection;
    }

    private List<TranslateMode> getTranslateMode()
    {
        ArrayList<TranslateMode> modeList = new ArrayList<TranslateMode>();
        IPreferenceStore mStore = ETranslatorPlugin.getDefault().getPreferenceStore();
        int index = mStore.getInt("trans_from");
        String supportedLan[] = TranslateEngine.getInstance().getAllSupportedLan();
        String sourceLang = supportedLan[index];
        for (String target : TranslateEngine.getInstance().getToLans(sourceLang))
        {
            if(mStore.getBoolean("trans_to" + target))
            {
                TranslateMode mode = TranslateMode.getTranslateMode(sourceLang, target);
                if(mode == null)
                    LOG.debug("unsupported translate mode, source:" + sourceLang + " target:" + target);
                else
                    modeList.add(mode);
            }
        }

        return modeList;
    }

class TranslateWithProgress implements IRunnableWithProgress
{

    public void run(IProgressMonitor monitor)
        throws InvocationTargetException, InterruptedException
    {
        ArrayList<TranslateMode> modeList = (ArrayList<TranslateMode>)getTranslateMode();
        monitor.beginTask(ETranslatorResources.getString("progress.title"), modeList.size());
        for(int i = 0; i < modeList.size(); i++)
        {
            SubProgressMonitor subMonitor = new SubProgressMonitor(monitor, 1);
            try
            {
                TranslateCore.translateResourceFile(sourceFile, (TranslateMode)modeList.get(i), subMonitor);
            }
            catch(Exception e)
            {
                Display display = PlatformUI.getWorkbench().getDisplay();
                ErrorDialogRun run = new ErrorDialogRun();
                run.e = e;
                display.asyncExec(run);
                return;
            }
            try
            {
                IFile selFile = (IFile)((StructuredSelection)curSel).getFirstElement();
                selFile.getProject().refreshLocal(2, null);
            }
            catch(CoreException _ex) { }
        }

        monitor.done();
    }

    public String sourceFile;

}

/**
 * this class is used to show error message
 *
 */
class ErrorDialogRun implements Runnable
{

	public Exception e;
	
    public void run()
    {
        if(e instanceof IOException)
            MessageDialog.openError(null, ETranslatorResources.getString("error.dialog.title"), ETranslatorResources.getString("error.dialog.msg.network") + " " + e.toString());
        else
            MessageDialog.openError(Display.getCurrent().getActiveShell(), ETranslatorResources.getString("error.dialog.title"), ETranslatorResources.getString("error.dialog.msg.general") + " " + e.toString());
    }


}
}
